package com.mingtu.guards.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.SPTools;
import com.mingtu.common.utils.UIUtils;
import com.mingtu.guards.R;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.utils.MyConstant;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMSendCallback;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class SendTaskAddActivity extends MyBaseActivity {

    @BindView(R.id.edit_task_name)
    EditText editTaskName;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.layout_people)
    LinearLayout layoutPeople;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.layout_time)
    LinearLayout layoutTime;
    @BindView(R.id.edit_task)
    EditText editTask;
    @BindView(R.id.submit)
    Button submit;
    @BindView(R.id.tv_select_people)
    TextView tvSelectPeople;
    @BindView(R.id.tv_select_num)
    TextView tvSelectNum;
    @BindView(R.id.layout_select_people)
    LinearLayout layoutSelectPeople;

    private int MyRequestCode = 100;
    private JSONArray peopleInfoList = null;
    private String userName;
    private String userId;
    private String taskName;
    private String taskContent;
    private Timer timer;
    private String[] peopleArray = null;
    private String[] mobileArray = null;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_send_task_add;
    }

    @Override
    protected void initView() {
        setModuleTitle("新增下发");
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void getData() {
        userName = SPStaticUtils.getString(SPTools.userName);
        userId = SPStaticUtils.getString(SPTools.userId);
    }


    @OnClick({R.id.layout_people, R.id.layout_time, R.id.submit, R.id.layout_select_people})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_people:
                IntentUtils.getInstance().readyGoForResult(SendTaskAddActivity.this, SelectPeopleActivity.class, MyRequestCode);
                break;
            case R.id.layout_time:
                initTimePicker();
                break;
            case R.id.submit:
                taskName = UIUtils.getEditText(editTaskName);
                taskContent = UIUtils.getEditText(editTask);
                if (StringUtils.isEmpty(taskName)) {
                    ToastUtils.showLong("请填写任务名字！");
                    return;
                }

                if (StringUtils.isEmpty(UIUtils.getTextView(tvTime)) || tvTime.getText().toString().equals(getResources().getString(R.string.text_chose_time))) {
                    ToastUtils.showLong("请选择截止时间！");
                    return;
                }

                if (StringUtils.isEmpty(taskContent)) {
                    ToastUtils.showLong("请填写任务内容！");
                    return;
                }

                if (peopleInfoList == null) {
                    ToastUtils.showLong("请选择任务接收人员！");
                    return;
                }
                addSendTask();
                break;
            case R.id.layout_select_people:
                if (peopleArray != null) {
                    if (peopleArray.length > 0) {
                        new XPopup.Builder(this)
                                //                        .maxWidth(600)
                                .maxHeight(1000)
                                .isDarkTheme(false)
                                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                                .asCenterList("接收人员", peopleArray,
                                        new OnSelectListener() {
                                            @Override
                                            public void onSelect(int position, String text) {

                                            }
                                        })
                                .show();
                    }
                }

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == MyRequestCode) {
            if (data != null) {
                String infoStr = data.getStringExtra("infoStr");
                JSONObject object = JSON.parseObject(infoStr);
                peopleInfoList = object.getJSONArray("peopleInfoList");

                if (peopleInfoList != null) {
                    int size = peopleInfoList.size();
                    if (size > 0) {
                        layoutSelectPeople.setVisibility(View.VISIBLE);

                        String str = "";

                        if (size > 3) {
                            for (int i = 0; i < 3; i++) {
                                JSONObject objectItem = (JSONObject) peopleInfoList.get(i);
                                String userName = objectItem.getString("name");
                                if (i < 2) {
                                    userName = userName + "，";
                                }
                                str += userName;
                            }

                            tvSelectPeople.setText("已选择" + str + "等");
                            tvSelectNum.setText("共" + size + "人");
                        } else {
                            for (int i = 0; i < size; i++) {
                                JSONObject objectItem = (JSONObject) peopleInfoList.get(i);
                                String userName = objectItem.getString("name");
                                if (i < size - 1) {
                                    userName = userName + "，";
                                }
                                str += userName;
                            }

                            tvSelectPeople.setText("已选择" + str);
                            tvSelectNum.setText("共" + size + "人");
                        }

                        peopleArray = new String[size];
                        mobileArray = new String[size];
                        for (int i = 0; i < size; i++) {
                            JSONObject objectItem = (JSONObject) peopleInfoList.get(i);
                            String name = objectItem.getString("name");
                            String mobile = objectItem.getString("mobile");
                            peopleArray[i] = name;
                            mobileArray[i] = mobile;
                        }
                    }
                }
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }

    //时间选择器
    private void initTimePicker() {
        //获取系统的日期
        Calendar selectedDate = Calendar.getInstance();
        int year = selectedDate.get(Calendar.YEAR);
        int month = selectedDate.get(Calendar.MONTH);
        int day = selectedDate.get(Calendar.DAY_OF_MONTH);
        int hour = selectedDate.get(Calendar.HOUR_OF_DAY);
        int minute = selectedDate.get(Calendar.MINUTE);
        int second = selectedDate.get(Calendar.SECOND);


        Calendar startDate = Calendar.getInstance();

        //结束时间
        Calendar endDate = Calendar.getInstance();
        endDate.add(Calendar.YEAR, 0);
        endDate.add(Calendar.MONTH, 3);
        endDate.add(Calendar.DAY_OF_MONTH, 0);
        endDate.add(Calendar.HOUR_OF_DAY, 0);
        endDate.add(Calendar.MINUTE, 0);
        endDate.add(Calendar.SECOND, 0);


        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调

                Calendar deadlineTime = Calendar.getInstance();
                deadlineTime.setTime(date);
                int sYear = deadlineTime.get(Calendar.YEAR);
                int sMonth = deadlineTime.get(Calendar.MONTH);
                int sDay = deadlineTime.get(Calendar.DAY_OF_MONTH);

                deadlineTime.set(sYear, sMonth, sDay, 23, 59, 59);

                Date myDate = deadlineTime.getTime();

                String deadlineTimeStr = UIUtils.getTime2(myDate);
                tvTime.setText(deadlineTimeStr);
                tvTime.setTextColor(getResources().getColor(R.color.text_color333));

            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})//分别对应年月日时分秒，默认全部显示
                .setContentTextSize(20)//滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setTitleBgColor(getResources().getColor(R.color.black_eee))
                .setCancelColor(getResources().getColor(R.color.text_cancel_color))
                .setSubmitColor(getResources().getColor(R.color.text_submit_color))
                .setTextColorCenter(getResources().getColor(R.color.colorPrimary))
                .setBgColor(Color.WHITE)
                .isDialog(true)
                .setOutSideColor(getResources().getColor(R.color.transparent))
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")
                .build();


        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);
            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
            }
        }

        pvTime.show();
    }


    /**
     * 添加下发任务
     */
    private void addSendTask() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("senderName", userName);
        hashMap.put("userId", userId);
        hashMap.put("name", taskName);
        hashMap.put("finishTime", tvTime.getText());
        hashMap.put("memo", taskContent);
        hashMap.put("assignmentUserEntityList", peopleInfoList);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_ADD_SEND_TASK)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {


                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                ToastUtils.showLong("下发成功！");
                                //实例化Timer类 ,守护线程，不在后台一直运行

                                String message = "您有一条任务消息";
                                for (int i = 0; i < mobileArray.length; i++) {
                                    String mobiie = mobileArray[i];
                                    if (!StringUtils.isEmpty(mobiie)) {
                                        V2TIMMessage v2TIMMessage = V2TIMManager.getMessageManager().createCustomMessage(message.getBytes());
                                        String msgID = V2TIMManager.getMessageManager().sendMessage(v2TIMMessage, mobiie, null,
                                                V2TIMMessage.V2TIM_PRIORITY_DEFAULT, false, null, new V2TIMSendCallback<V2TIMMessage>() {
                                                    @Override
                                                    public void onProgress(int progress) {
                                                        MyLogUtil.e("testtest", "sendMessage onProgress:" + progress);
                                                    }

                                                    @Override
                                                    public void onError(int code, String desc) {
                                                        MyLogUtil.e("testtest", "sendMessage onError:" + desc);
                                                    }

                                                    @Override
                                                    public void onSuccess(V2TIMMessage v2TIMMessage) {
                                                        MyLogUtil.e("testtest", "sendMessage onSuccess:" + v2TIMMessage.getMsgID());
                                                    }
                                                });
                                    }
                                }

                                timer = new Timer(true);
                                timer.schedule(new TimerTask() {
                                    public void run() {
                                        setResult(200);
                                        ActivityUtil.removeActivity(SendTaskAddActivity.this);
                                    }
                                }, Constant.TIMER_TIME);
                            }
                        }
                    }
                });
    }


}